#include "Mini58Series.h"
#include "timer.h"

#include "string.h"
#include "bsp_timer0.h"

static Task_time taskTime;
static uint32_t uptimems = 0;

static void timer0_ParamInit(void);
void Timer0_InitHard(void) {
  timer0_ParamInit();

  SYS_ResetModule(TMR0_RST);

  /* Enable IP clock */
  CLK_EnableModuleClock(TMR0_MODULE);

  /* Select IP clock source */
  CLK_SetModuleClock(TMR0_MODULE, CLK_CLKSEL1_TMR0SEL_HIRC, 0);

  // Set timer 0 working 1Hz in periodic mode
  TIMER_Open(TIMER0, TIMER_PERIODIC_MODE, 996);

  // Enable timer interrupt
  TIMER_EnableInt(TIMER0);
  NVIC_EnableIRQ(TMR0_IRQn);

  // Start Timer 0
  TIMER_Start(TIMER0);
}

Task_time* timer0_taskTimer_get(void) { return &taskTime; }

static void timer0_ParamInit(void) {
  uptimems = 0;

  memset((uint8_t*)&taskTime, 0, sizeof(Task_time));
}
uint32_t UptimeMs(void) { return uptimems; }

void TMR0_IRQHandler(void) {
  uptimems++;

  if (taskTime.cnt_flag_1ms < 10000) {
    taskTime.cnt_flag_1ms++;
  }

  if (++taskTime.cnt_10ms >= 10) {
    taskTime.cnt_10ms = 0;
    taskTime.flag_10ms = 1;
  }
  if (++taskTime.cnt_20ms >= 20) {
    taskTime.cnt_20ms = 0;
    taskTime.flag_20ms = 1;
  }
  if (++taskTime.cnt_50ms >= 50) {
    taskTime.cnt_50ms = 0;
    taskTime.flag_50ms = 1;
  }
  if (++taskTime.cnt_100ms >= 100) {
    taskTime.cnt_100ms = 0;
    taskTime.flag_100ms = 1;
  }
  if (++taskTime.cnt_250ms >= 250) {
    taskTime.cnt_250ms = 0;
    taskTime.flag_250ms = 1;
  }
  if (++taskTime.cnt_500ms >= 500) {
    taskTime.cnt_500ms = 0;
    taskTime.flag_500ms = 1;
  }

  if (++taskTime.cnt_1s >= 1000) {
    taskTime.cnt_1s = 0;
    taskTime.flag_1s = 1;
  }

  // clear timer interrupt flag
  TIMER_ClearIntFlag(TIMER0);
}
